/*
 * File Name:    checkNMEA.c
 *
 * Author:        Yoshinobu Date
 * Creation Date: Tuesday, August 09 2011, 11:35 
 * Last Modified: Tuesday, August 09 2011, 11:49
 * 
 * File Description:
 *
 */
#include <string.h>
#include <stdio.h>

#include "checkNMEA.h"

const char code[58][3] = {"AAM","ALM","APA","APB","ASD","BEC","BOD","BWC","BWR","BWW","DBT","DCN","DPT","FSI","GGA","GLC","GLL","GSA","GSV","GXA","HDG","HDT","HSC","LCD","MTA","MTW","MWD","MWV","OLN","OSD","R00","RMA","RMB","RMC","ROT","RPM","RSA","RSD","RTE","SFI","STN","TRF","TTM","VBW","VDR","VHW","VLW","VPW","VTG","WCV","WNC","WPL","XDR","XTE","XTR","ZDA","ZFO","ZTG"};

unsigned char checkSum(char* nmeastr)
{
    int counter = 1;
    unsigned char cs = 0;
    int bSize = strlen(nmeastr);
    
    while (counter < (bSize - 3) ) {
        cs ^= (unsigned char)nmeastr[counter];
        counter++;
    }
    return cs;
}

int validate(char* nmeastr)
{	char cs[3] = {'\0'};
	int ln;
	sprintf(cs,"%02X", checkSum(nmeastr) );
	ln = strlen(nmeastr);
    printf("%c,%c,%c,%c\n",nmeastr[ln-2],nmeastr[ln-1],cs[0],cs[1]);
	return ( (nmeastr[ln-2] == cs[0]) && (nmeastr[ln-1] == cs[1]) );
}

short int typeCode2Num(char *nmeastr)
{
    char str[3];
	short int codeNum;
    sscanf(nmeastr, "$%*2s%3s%*s",str);
    codeNum = 0;
    while (str[0] > code[codeNum][0]) {
        codeNum++;
    }
    while (str[1] > code[codeNum][1]) {
        codeNum++;
    }
    while (str[2] > code[codeNum][2]) {
        codeNum++;
    }
    if (!((str[0] == code[codeNum][0])&&(str[1] == code[codeNum][1])&&(str[2] == code[codeNum][2]))) {
        codeNum = -1;
    }
    return codeNum;
}